﻿using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading;
using AnjLab.SyncIT.App.Properties;
using Settings=AnjLab.SyncIT.App.Properties.Settings;

namespace AnjLab.SyncIT.App
{
    static class UpdatesChecker
    {
        static readonly Regex VersionRegex = new Regex(@"AnjLab.SyncIT.App-(?<Version>(?<Major>\d+)\.(?<Minor>\d+)\.(?<Build>\d+)\.(?<Revision>\d+))");

        public static Version CurrentAssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version;
            }
        }

        public static Version GetLatestVersion()
        {
            var versions = new List<Version>();
            try
            {
                var req =
                    (HttpWebRequest)WebRequest.Create("http://code.google.com/p/outlooktrac/downloads/list");
                var response = (HttpWebResponse)req.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var page = reader.ReadToEnd();
                    var matches = VersionRegex.Matches(page);
                    foreach (Match match in matches)
                    {
                        var v = new Version(match.Groups["Version"].Value);
                        versions.Add(v);
                    }
                }
            }
            catch
            {
                return null;
            }
            versions.Sort();
            return versions.Count == 0 ? new Version("0.0.0.0") : versions[versions.Count - 1];
        }

        public static event EventHandler NewVersionIsAvailable;

        public static void StartNewVersionChecking()
        {
            if ((DateTime.Now - Properties.Settings.Default.UpdatesLastCheck).TotalDays < 7)
                return;

            var th = new Thread(delegate(object o)
                                   {
                                       Thread.Sleep(15 * 1000);
                                       Version latestVersion = GetLatestVersion();
                                       if (latestVersion == null)
                                           return;

                                       Settings.Default.UpdatesLastCheck = DateTime.Now;

                                       if (latestVersion > CurrentAssemblyVersion && NewVersionIsAvailable != null)
                                           NewVersionIsAvailable(null, EventArgs.Empty);
                                   }) {IsBackground = true, Priority = ThreadPriority.BelowNormal};

            th.Start();
        }
    }
}